package com.able.concurrency.t2;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author abel.he
 * @data 2018/8/18 12:52
 * @describe 公平锁 测试的基础是需要提供线程进行足够时间反应 不然也不会产生线程交替出现的情况
 */
public class Test4 {
    public static void main(String[] args) {
//        TestReenTrantLock t = new TestReenTrantLock();
        TestSync t = new TestSync();

        Thread thread1 = new Thread(t, "Thread1");
        Thread thread2 = new Thread(t, "Thread2");
        thread1.start();
        thread2.start();
    }
}

class TestReenTrantLock extends Thread{
    private static Lock lock = new ReentrantLock(true);
    @Override
    public void run() {
        for (int i = 0; i < 10; i++) {
            lock.lock();
            try {
//                TimeUnit.SECONDS.sleep(1);
                Thread.sleep(100);
                System.out.println(Thread.currentThread().getName() + " 获取资源" + i);

            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                lock.unlock();
            }
        }
    }
}

class TestSync extends Thread{
    @Override
    public void run() {
        for (int i = 0; i < 10; i++) {
            synchronized (this) {
                System.out.println(Thread.currentThread().getName() + "所获取的资源是" + i);
            }
        }
    }
}
